/*
 * ChatFrm.java
 *
 * Created on 26 de septiembre de 2007, 08:01 PM
 */

package inc.jmc.cyberboard.chat;


import inc.jmc.cyberboard.common.ImageLoader;
import inc.jmc.cyberboard.common.NumFormat;

import java.awt.Dimension;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;

import javax.swing.JEditorPane;
import javax.swing.JOptionPane;

import org.apache.log4j.Logger;

/**
 *
 * @author  JOlguin01
 */
public class ChatFrm extends javax.swing.JInternalFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1698684112805275883L;
	public static final Dimension compacta=new Dimension(336,408);
	static Logger logger = Logger.getLogger(ChatFrm.class.getName());
    /**
	 * @return the destinoTxt
	 */
	public javax.swing.JTextField getDestinoTxt() {
		return destinoTxt;
	}

	/**
	 * @param destinoTxt the destinoTxt to set
	 */
	public void setDestinoTxt(javax.swing.JTextField destinoTxt) {
		this.destinoTxt = destinoTxt;
	}

	/**
	 * @return the nickTxt
	 */
	public javax.swing.JTextField getNickTxt() {
		return nickTxt;
	}

	/**
	 * @param nickTxt the nickTxt to set
	 */
	public void setNickTxt(javax.swing.JTextField nickTxt) {
		this.nickTxt = nickTxt;
	}

	/** Creates new form ChatFrm */
    public ChatFrm() {
        initComponents();
        this.setFrameIcon(ImageLoader.images[ImageLoader.ICON_FRAME_MAIN]);
        try {
			ipLabel.setText(InetAddress.getLocalHost().toString().split("/")[1]);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
        this.setSize(compacta);
        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
        });
        
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        allChatTxt = new javax.swing.JEditorPane();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        destinoTxt = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        nickTxt = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        sendButton = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        minickTxt = new javax.swing.JTextField();
        ipLabel = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        textSend = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
        });

        jSplitPane1.setDividerLocation(100);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel1.setMinimumSize(new java.awt.Dimension(0, 100));
        jPanel1.setPreferredSize(new java.awt.Dimension(100, 100));
        allChatTxt.setEditable(false);
        allChatTxt.setContentType("text/html");
        jScrollPane1.setViewportView(allChatTxt);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jSplitPane1.setTopComponent(jPanel1);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel3.setLayout(null);

        jPanel3.setPreferredSize(new java.awt.Dimension(160, 100));
        jLabel1.setText("Ip destino");
        jPanel3.add(jLabel1);
        jLabel1.setBounds(10, 30, 70, 20);

        jPanel3.add(destinoTxt);
        destinoTxt.setBounds(10, 50, 130, 19);

        jLabel2.setText("Nick");
        jPanel3.add(jLabel2);
        jLabel2.setBounds(10, 70, 70, 14);

        jPanel3.add(nickTxt);
        nickTxt.setBounds(10, 90, 130, 19);

        jButton1.setText("Clear");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanel3.add(jButton1);
        jButton1.setBounds(100, 10, 57, 23);

        sendButton.setMnemonic('S');
        sendButton.setText("Send");
        sendButton.setToolTipText("Alt-S para enviar mensaje");
        sendButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendButtonActionPerformed(evt);
            }
        });

        jPanel3.add(sendButton);
        sendButton.setBounds(10, 120, 130, 23);

        jPanel5.setLayout(null);

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("LocalHost"));
        jLabel3.setText("IP:");
        jPanel5.add(jLabel3);
        jLabel3.setBounds(20, 20, 30, 20);

        jLabel4.setText("Mi nick");
        jPanel5.add(jLabel4);
        jLabel4.setBounds(20, 60, 50, 14);

        minickTxt.setText("localhost");
        jPanel5.add(minickTxt);
        minickTxt.setBounds(20, 80, 100, 19);

        ipLabel.setEditable(false);
        jPanel5.add(ipLabel);
        ipLabel.setBounds(20, 40, 100, 19);

        jPanel3.add(jPanel5);
        jPanel5.setBounds(10, 150, 140, 110);

        jPanel2.add(jPanel3, java.awt.BorderLayout.EAST);

        jPanel4.setLayout(new java.awt.BorderLayout());

        jPanel4.setPreferredSize(new java.awt.Dimension(100, 100));
        textSend.setColumns(20);
        textSend.setFont(new java.awt.Font("Tahoma", 0, 11));
        textSend.setRows(5);
        jScrollPane2.setViewportView(textSend);

        jPanel4.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jPanel2.add(jPanel4, java.awt.BorderLayout.CENTER);

        jSplitPane1.setRightComponent(jPanel2);

        getContentPane().add(jSplitPane1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained

        this.textSend.requestFocus();
        System.out.println("FOCUS ESTABLECIDO --- this.textSend.requestFocus();");
    }//GEN-LAST:event_formFocusGained

    public String prepareHtmlColors(String nick1,String mensaje)
    {
    	String hora = NumFormat.sdf_hh_mm_ss.format(new Date());
    	String preparedtxt="<font color=\"#FF0000\" size=\"3\" face=\"Arial, Helvetica, sans-serif\">[<strong>"+hora+"</strong>(&lt;o&gt;)<strong>"+nick1+"</strong>] : </font><font color=\"#000000\" size=\"3\" face=\"Arial, Helvetica, sans-serif\">"+mensaje+"</font><br>";
    	//String preparedtxt="<font color=\"#0000FF\" size=\"3\" face=\"Arial, Helvetica, sans-serif\">["+nick1+"]:  "+mensaje+"</font><br>";
    	return preparedtxt;
    }
    private JEditorPane txtplain=new JEditorPane();
    public int calcPositionCaret(JEditorPane htmlpane) 
    { 
    	txtplain.setContentType("text/plain"); 
    	htmlpane.select(0, htmlpane.getText().length());
    	String aaa = htmlpane.getSelectedText();
    	txtplain.setText(aaa);
    	return aaa.length();
    } 
    
    public StringBuffer allChatTxtContent=new StringBuffer();
    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButtonActionPerformed

    	String mensaje=textSend.getText();
        int puertodestino = IncomingMessagesThread.LISTENING_PORT;
        if(mensaje.equals(""))
            {
                JOptionPane.showMessageDialog(this,"Mensaje Vacio","Error de envio",JOptionPane.ERROR_MESSAGE);
                textSend.requestFocus();
                return;
         
            }
        ///si el destinatario no esta vacion, entonces lo enviamos
        if(getDestinoTxt().getText()!=null && !getDestinoTxt().getText().equals(""))
        {
        	String nick1=this.nickTxt.getText();
        	if(nick1==null||nick1.equals(""))
        		nick1="localhost";

            this.sendMessage(getDestinoTxt().getText(),puertodestino,mensaje);
            //String preparedtxt="["+nick1+"]:  "+mensaje+"\n";
            String preparedtxt=this.prepareHtmlColors(nick1, mensaje);
            String wrapptxt=allChatTxtContent.append(preparedtxt).toString();
            
            
            logger.info("TEXTO PARA JEDITORPANE:"+wrapptxt);
            allChatTxt.setText(wrapptxt);
            //String text1 = allChatTxt.getText();
            allChatTxt.setCaretPosition(this.calcPositionCaret(allChatTxt));
            textSend.setText("");
            jPanel1.updateUI();
            
            
        }
        else
        {
            JOptionPane.showMessageDialog(this,"Falta destinatario","Error de envio",JOptionPane.ERROR_MESSAGE);
        }
        textSend.requestFocus();
        
    }//GEN-LAST:event_sendButtonActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        getAllChatTxt().setText("");
    }//GEN-LAST:event_jButton1ActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ChatFrm().setVisible(true);
            }
        });
    }

    public javax.swing.JEditorPane getAllChatTxt() {
        return allChatTxt;
    }
    public void sendMessage(String ip,int port,String mensaje)
    {
        
        Socket echoSocket = null;
        PrintWriter out = null;
        //BufferedReader in = null;

        try {
            echoSocket = new Socket(ip, port);
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            out.println(mensaje);
            out.close();
            echoSocket.close();
            logger.debug("El mensaje se esta mandando a esta direccion:"+echoSocket.getInetAddress());
            logger.debug("El puerto a donde se envia es:"+echoSocket.getPort());
            logger.debug("Mensaje enviado es:"+mensaje);
        } 
        catch (UnknownHostException e) {
            logger.debug("Host desconocido: "+ip);
            JOptionPane.showMessageDialog(this,"Excepcion:"+e.getMessage(),"Host desconocido",JOptionPane.ERROR_MESSAGE);
            
        } catch (IOException e) {
            logger.debug("No se establecio conexion IO con :"+ip);
            JOptionPane.showMessageDialog(this,"Excepcion:"+e.getMessage(),"No se establecio conexion",JOptionPane.ERROR_MESSAGE);
            
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JEditorPane allChatTxt;
    private javax.swing.JTextField destinoTxt;
    private javax.swing.JTextField ipLabel;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextField minickTxt;
    private javax.swing.JTextField nickTxt;
    private javax.swing.JButton sendButton;
    private javax.swing.JTextArea textSend;
    // End of variables declaration//GEN-END:variables
	public javax.swing.JPanel getJPanel1() {
		return jPanel1;
	}
    
}
